package com.weme.common.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.text.TextUtils
import android.util.DisplayMetrics
import android.util.Log
import android.util.Size
import android.view.WindowManager
import androidx.core.content.ContextCompat
import okhttp3.*
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.URLEncoder


val Context.displayMetrics: DisplayMetrics
    get() {
        val wm: WindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val dm = DisplayMetrics();
        wm.defaultDisplay.getRealMetrics(dm)
        return dm
    }

/**
 * 屏幕尺寸
 */
val Context.deviceSize: Size
    get() = Size(displayMetrics.widthPixels, displayMetrics.heightPixels)

fun Context.dp2px(dp: Int): Int {
    return (displayMetrics.density * dp + 0.5f).toInt()
}

fun Context.ktGetColorId(colorId: Int): Int {
    return ContextCompat.getColor(this, colorId)
}

fun Context.sp2px(spValue: Int): Int {
    val fontScale: Float = resources.displayMetrics.scaledDensity
    return (spValue * fontScale + 0.5f).toInt()
}

fun Int.dpToPx(context: Context): Int {
    return (this * context.resources.displayMetrics.density).toInt()
}

fun Float.dpToPx(context: Context): Int {
    return (this * context.resources.displayMetrics.density).toInt()
}

fun Context.dpToPx(spValue: Int): Int {
    return (spValue * this.resources.displayMetrics.density).toInt()
}

fun Context.isNetworkAvailable(): Boolean {
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val activeNetworkInfo: NetworkInfo? = connectivityManager.activeNetworkInfo
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting
}


fun downloadImageAsBitmap(url: String, callback: (String?) -> Unit) {
    try {
        val client = OkHttpClient()

        val request = Request.Builder().url(url).build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) { // 下载失败时调用回调并传入 null
                callback(null)
            }

            override fun onResponse(call: Call, response: Response) {
                if (!response.isSuccessful) { // 响应不成功时调用回调并传入 null
                    callback(null)
                    return
                }

                // 获取响应的字节数组并转换为 Base64 字符串
                val bytes = response.body.bytes()
                val base64String = byteArrayToBase64(bytes)
                callback("data:image/png;base64,$base64String")
            }
        })
    }catch (e:Exception){
        callback(null)
    }

}

fun byteArrayToBase64(byteArray: ByteArray): String { // 使用 Base64 类的 encodeToString 方法将字节数组转换为 Base64 字符串
    return android.util.Base64.encodeToString(byteArray, android.util.Base64.DEFAULT)
}

fun base64ToBitmap(base64String: String): Bitmap? {
    try { // 解码 Base64 字符串为字节数组
        val decodedBytes: ByteArray = android.util.Base64.decode(base64String, android.util.Base64.DEFAULT)

        // 将字节数组转换为 Bitmap 对象
        return BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

fun Context.isVip(): Boolean {
    return UserMKHelper.decodeLong(UserMKHelper.VIP_LEVEL) > 0L
}

private fun encodeUrl(url: String): String? {
    return try {
        URLEncoder.encode(url, "UTF-8")
    } catch (e: UnsupportedEncodingException) {
        e.printStackTrace()
        url // Return the original URL if encoding fails
    }
}
fun downloadMp4(url: String,name:String, callback: (Boolean?) -> Unit) {

    if(TextUtils.isEmpty(url)){
        callback.invoke(null)
        return
    }
    Log.e("dow","下载地址和路径"+ name )
    if (!FileUtils.isFileExit(FileUtils.fileUrl + name+".mp4")) {
        try {
            val client = OkHttpClient()
            val request = Request.Builder().url(url).build()

            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) { // 下载失败时调用回调并传入 null
                    Log.e("dow","下载失败"+e.message)
                    callback(null)
                }

                override fun onResponse(call: Call, response: Response) {
                    if (!response.isSuccessful) { // 响应不成功时调用回调并传入 null
                        callback(null)
                        Log.e("dow","下载失败")
                        return
                    }
                    val writtenToDisk: Boolean = FileUtils.writeResponseBodyToDisk(response.body, name+".mp4")
                    Log.e("dow","成功")
                    callback.invoke(writtenToDisk)

                }
            })
        }catch (e:Exception){
            callback(null)
            Log.e("tag","下载失败"+e.message)
        }
    }else{
        Log.e("dow","下载过了")
    }
}


private var lastCallTime: Long = 0

fun canCallAgain(interval: Long): Boolean {
    val currentTime = System.currentTimeMillis()
    return if (currentTime - lastCallTime >= interval) {
        lastCallTime = currentTime
        true
    } else {
        false
    }
}
